﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using PH_Zu_DataUpload_Auto.Properties;
using Sunny.UI;
using System;
using System.Configuration;
using System.Net.Http;
using System.Windows.Forms;

namespace PH_Zu_DataUpload_Auto
{
    public partial class Main : UIForm
    {

        public Main()
        {
            InitializeComponent();

            uiTextBox2.Text = ConfigurationManager.AppSettings["User"].ToString();
            uiTextBox1.Text = ConfigurationManager.AppSettings["ResourceNo"].ToString();

            this.loadModel();
        }


        private void uiSwitch1_ValueChanged(object sender, bool value)
        {
            if (value)
            {
                string model = uiComboBox1.Text;
                string shifts = uiComboBox2.Text;
                if (shifts == "" || model == "")
                {
                    MessageBox.Show("型号或班次未选择，锁定失败！！");
                    this.uiSwitch1.Active = false;
                    return;
                }
                uiComboBox1.ReadOnly = true;
                uiComboBox2.ReadOnly = true;
            }else
            {
                uiComboBox1.ReadOnly = false;
                uiComboBox2.ReadOnly = false;
            }
        }

        private void uiSwitch2_ValueChanged(object sender, bool value)
        {
            if (value)
            {
                if (!this.uiSwitch1.Active)
                {
                    MessageBox.Show("数据未锁定，开始失败！！");
                    this.uiSwitch2.Active = false;
                    return;
                }
                timer1.Interval = int.Parse(ConfigurationManager.AppSettings["UploadInterval"].ToString());
                timer1.Start();
                this.uiSwitch1.ReadOnly = true;
            }
            else
            {
                timer1.Stop();
                this.uiSwitch1.ReadOnly = false;
            }
        }

        private async void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!this.uiSwitch2.Active)
                    timer1.Stop();
                Mysql mySql = new Mysql();
                // 执行查询
                string sql = "SELECT * FROM tb_batteryweight A left join tb_shengchan B on A.ssScID = B.ID left join tb_tj C on A.ssTjID = C.ID  WHERE bh != \"NULL\" AND zyh_rq IS NOT NULL AND mes_flag = 0  ORDER BY A.ID LIMIT 10";

                Mysql upMySql = new Mysql();
                string upSql = "UPDATE tb_batteryweight SET mes_flag = 1 WHERE ID = @Id";
                MySqlCommand cmd = new MySqlCommand(sql, mySql.sqlConnection);
                int rowCount = Convert.ToInt32(cmd.ExecuteScalar());
                if (rowCount == 0)
                    this.writeLog("查询可上传电芯集合为空【执行中】" + DateTime.Now.ToString());
                MySqlDataReader reader = cmd.ExecuteReader();
                MesHttp mesHttp = new MesHttp();

                while (reader.Read())
                {
                    string id = reader["ID"].ToString();
                    HttpResponseMessage responseMessage = await mesHttp.upload(ConfigurationManager.AppSettings["Site"].ToString(), ConfigurationManager.AppSettings["User"].ToString(), ConfigurationManager.AppSettings["ResourceNo"].ToString(), "ZY001", "ZY", "", "", reader["bh"].ToString(), reader["zyq_rq"].ToString(), uiComboBox2.Text, int.Parse(reader["hg"].ToString()) == 1 ? "OK" : "NG", reader["scBh"].ToString(),
                        reader["tjBh"].ToString(), reader["gjzb"].ToString(), reader["disNumber"].ToString(), reader["djyph"].ToString(), reader["zyq_zl"].ToString(), reader["zyh_zl"].ToString(), reader["zyl"].ToString(), reader["pcz"].ToString(), "", reader["zyq_czy"].ToString(), reader["zyh_rq"].ToString());
                    String result = await responseMessage.Content.ReadAsStringAsync();
                    MesHttpResult mesHttpResult = JsonConvert.DeserializeObject<MesHttpResult>(result);
                    if (!mesHttpResult.status)
                    {
                        FlaseHttpResult fHttpResult = JsonConvert.DeserializeObject<FlaseHttpResult>(result);
                        this.writeLog("上传失败【条码：" + reader["bh"].ToString() + " 注液后时间：" + reader["zyh_rq"].ToString() + "】||" + DateTime.Now);
                        this.writeLog("原因" + fHttpResult.message);
                    }
                    else
                    {
                        this.writeLog("上传成功【条码：" + reader["bh"].ToString() + " 注液后时间：" + reader["zyh_rq"].ToString() + "】||" + DateTime.Now);
                        MySqlCommand upCmd = new MySqlCommand(upSql, upMySql.sqlConnection);
                        upCmd.Parameters.AddWithValue("@Id", id);
                        int i = upCmd.ExecuteNonQuery();
                    }
                }
                // 关闭连接
                reader.Close();
            }catch (Exception ex)
            {
                timer1.Stop();
                this.uiSwitch2.Active = false;
                Logger.Error(ex);
                MessageBox.Show(ex.InnerException.Message);
            }
            
        }

        private void writeLog(String str)
        {
            Logger.Info(str);
            Log.Invoke(new Action(() => {
                Log.AppendText(str + "\r\n");
                Log.SelectionStart = Log.Text.Length;  // 设置光标位置到文本框末尾
                Log.ScrollToCaret();  // 滚动条跟随光标移动到最底部
            }
            ));

        }

        private async void loadModel()
        {
            try
            {
                MesHttp mesHttp = new MesHttp();
                HttpResponseMessage responseMessage = await mesHttp.getModelList();
                String result = await responseMessage.Content.ReadAsStringAsync();
                MesHttpResult mesHttpResult = JsonConvert.DeserializeObject<MesHttpResult>(result);
                if (!mesHttpResult.status)
                {
                    FlaseHttpResult fHttpResult = JsonConvert.DeserializeObject<FlaseHttpResult>(result);
                    MessageBox.Show(fHttpResult.message);
                }
                else
                {
                    TModelHttpResult modelHttpResult = JsonConvert.DeserializeObject<TModelHttpResult>(result);
                    Model[] models = modelHttpResult.result;
                    foreach (Model model in models)
                    {
                        this.uiComboBox1.Items.Add(model.PML_NO);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                MessageBox.Show(ex.InnerException.Message);
            }
        }
    }
}
